package com.zhiqianbao.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.ZhiMaNew;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.view.ProcessProgressBarView;

import java.util.HashMap;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;

/**
 * Created by 子龙 on 2017/9/22.
 */

public class ZhiMaActivity extends BaseActivity {
    public static final int DATA_FILED=0x123;
    public static final int DATA_SCUESSFUL=0x124;
    private Gson gson = new Gson();
    private WebView mtudent_rate_webview;
    private TextView topbar_textview_title;
    private SharedPreferanceUtils sharedPreferanceUtils;
    private  Button button;
    private ProcessProgressBarView processView;
    private LinearLayout loading_layout;
    private boolean isShow=false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_zhima);
        intView();
        initData();
    }



    private void initData() {
        showWaitDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/api/zhima/getAuthorizeUrl",
                        mapParams, ZhiMaActivity.this);
                if (StringUtils.isBlank(result)) {
                    message.what = DATA_FILED;
                } else {
                    message.what = DATA_SCUESSFUL;
                    ZhiMaNew data =gson.fromJson(result, ZhiMaNew.class);
                    message.obj = data;
                }
                postHandler.sendMessage(message);
            }
        }).start();
    }

    private void intView() {
         button = (Button) findViewById(R.id.button_return);
        loading_layout = (LinearLayout) findViewById(R.id.loading_layout);
            button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        sharedPreferanceUtils = new SharedPreferanceUtils(this);
        mtudent_rate_webview = (WebView) findViewById(R.id.zhima_layout);
        topbar_textview_title = (TextView) findViewById(R.id.topbar_textview_title);
        topbar_textview_title.setText("芝麻信用");
        processView= (ProcessProgressBarView) findViewById(R.id.process_layout);
        //芝麻开启状态,1开启，0未开启
        String zhimaOpenOrClose = sharedPreferanceUtils.getZhimaOpenOrClose();
        if("1".equals(zhimaOpenOrClose)){
            processView.openZhiMaProcess(ProcessProgressBarView.IS_SHOW_ZHIMA,3);
        }
        WebSettings webSettings = mtudent_rate_webview.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultFontSize(16); //支持通过JS打开新窗口
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(false);
        mtudent_rate_webview.getSettings().setSupportMultipleWindows(false);
        //通过js与本地接口交互
        mtudent_rate_webview.addJavascriptInterface(this, "zhima");

        mtudent_rate_webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

            }

            @Override
            public void onPageFinished(WebView view, String url) {


            }
        });

        mtudent_rate_webview.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根
                try{
                    if (!TextUtils.isEmpty(String.valueOf(newProgress))){
                        if(newProgress==100){
                            if(!isShow){
                                isShow=true;
                                verificationZhiMaDialog();
                            }
                            loading_layout.setVisibility(View.GONE);
                        }else{
                            loading_layout.setVisibility(View.VISIBLE);
                        }
                    }

                }catch (Exception e){

                }

                super.onProgressChanged(view, newProgress);
            }
        });
    }
    @JavascriptInterface
    public void confimZhimaAuth(String status){
            String emergency = sharedPreferanceUtils.getEmergency();
            String jobState = sharedPreferanceUtils.getJobState();
            if (emergency.equals("1")||emergency.equals("2")){
                if (jobState.equals("1")||jobState.equals("2")){
                    finish();
                }
                else{
                    startActivity(new Intent(ZhiMaActivity.this,FourthActivity.class));
                    finish();
                }
            }else {
                startActivity(new Intent(ZhiMaActivity.this,ThirdActivity.class));
                finish();
            }

    }

    /**
     * 芝麻信用验证提示，验证芝麻信用增加借款额度
     */
    public void verificationZhiMaDialog() {
            final AlertDialog zhimaDialog = new AlertDialog.Builder(ZhiMaActivity.this, R.style.Dialog).create();
            zhimaDialog.show();

            View view = LayoutInflater.from(ZhiMaActivity.this).inflate(R.layout.dialog_express_coupon_layout, null);
            zhimaDialog.getWindow().setContentView(view);
            zhimaDialog.setCanceledOnTouchOutside(false);
            TextView repay_money = (TextView) view.findViewById(R.id.repay_money);
            Button button = (Button) view.findViewById(R.id.positiveButton);
            Button cacelButton = (Button) view.findViewById(R.id.cacelButton);
            repay_money.setText("芝麻信用认证有助于提高您的借款审批速度与信用额度！是否立即认证？");
            button.setText("认证");
            cacelButton.setText("不认证");
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    zhimaDialog.dismiss();
                }
            });

            cacelButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    zhimaDialog.dismiss();
                    nextZhiMaPage();
                }
            });
    }


    public void nextZhiMaPage() {
        String emergency = sharedPreferanceUtils.getEmergency();
        String jobState = sharedPreferanceUtils.getJobState();
        if (!TextUtils.isEmpty(emergency)) {
            if ("1".equals(emergency) || "2".equals(emergency)) {
                if ("1".equals(jobState) || "2".equals(jobState)) {
                    finish();
                } else {
                    startActivity(new Intent(ZhiMaActivity.this, FourthActivity.class));
                    finish();
                }
            } else {
                startActivity(new Intent(ZhiMaActivity.this, ThirdActivity.class));
                finish();
            }
        }
    }

    Handler postHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DATA_FILED:
                    closeWaitDialog();
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case DATA_SCUESSFUL:
                    ZhiMaNew response = (ZhiMaNew) msg.obj;
                    closeWaitDialog();
                    if (response!=null){
                        if (response.getCode().equals("0")){
                            showShortToast1(response.getMsg());
                            //加载需要显示的网页
                            if (!TextUtils.isEmpty(response.getData().getUrl())){
                                mtudent_rate_webview.loadUrl(response.getData().getUrl());
                            }


                        }else if (response.getCode().equals("1")){
                            showShortToast1(response.getMsg());
                        }
                    }
                    break;
            }

        }
    };
}
